package jcolorlinez;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

@SuppressWarnings("serial")
public class ChessPanel extends JPanel{
	public final static Color[] COLORS = new Color[]{Color.RED, Color.GREEN, Color.BLUE, Color.MAGENTA, Color.ORANGE, Color.CYAN}; 
	protected BoardFrame board = null;
	protected Grid.Cell cell = null;
	
	public ChessPanel(BoardFrame board, int row, int col) {
		this.board = board;
		this.cell = new Grid.Cell(row, col);

		this.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
		this.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				ChessPanel chess = (ChessPanel)e.getComponent();
				chess.board.grid.click(chess.cell.row, chess.cell.col);
			}			
		});
	}
	
	private int getValue() {
		return board.grid.get(cell);
	}
	private boolean isSelected() {
		return cell.equals(board.grid.getSelectedCell());
	}
	private int getSelectAnimationFrame() {
		return board.grid.getSelectAnimationFrame();
	}
	private Color getChessColor() {
		if (getValue() > 0) {
			return COLORS[getValue() - 1];
		} else {
			return null;
		}
	}
	@Override
	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		if (getChessColor() != null) {
			g.setColor(getChessColor());
			if (isSelected()) {
				switch (getSelectAnimationFrame() % 8) {
				case 0:
				case 3:
					g.fillOval(getWidth()/16, getHeight()/16, getWidth()*7/8, getHeight()*7/8);
					break;
				case 1:
				case 2:
					g.fillOval(getWidth()/16, getHeight()/8, getWidth()*7/8, getHeight()*7/8);
					break;
				case 4:
				case 5:
				case 6:
				case 7:
					g.fillOval(getWidth()/16, 0, getWidth()*7/8, getHeight()*7/8);
					break;
				}
			} else {
				g.fillOval(getWidth()/16, getHeight()/16, getWidth()*7/8, getHeight()*7/8);
			}
		}
		if (Main.DEBUG) {
			g.setColor(Color.BLACK);
			g.drawString(cell.row + ":" + cell.col, 1, 15);
		}
	}
	
	protected ChessPanel() {}
	public static class ShowOnly extends ChessPanel {
		public ShowOnly(BoardFrame board, int col) {
			this.board = board;
			this.cell = new Grid.Cell(Grid.ROW_FOR_NEW_CHESS, col);
			this.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
			this.setBackground(Color.DARK_GRAY);
		}
	}
}
